<route lang="json5" type="page">
	{
	layout: 'default',
	style: {
	navigationBarTitleText: '信息认证',
	navigationStyle: 'custom',
	disableScroll: true, // 微信禁止页面滚动
	'app-plus': {
	bounce: 'none', // 禁用 iOS 弹性效果
	},
	},
	}
</route>

<template>
	<PageLayout :navTitle="pageTitle" backRouteName="people">
		<!-- 用户信息认证 -->
		<wd-form v-if="userForm" style="z-index: 999;" custom-class="pt3" ref="form" :model="userModel">
			<view class="change-info-box">
				<wd-cell-group border>
					<wd-input readonly required label="用户名称：" prop="userName" clearable label-width="120px"
						v-model="userModel.userName" placeholder="请输入用户名称" :rules="[{ validator: rules.userName }]">
					</wd-input>
					<wd-picker required label="所属公司：" v-model="userModel.selecteddeparts" :columns="columns"
						:rules="[{ validator: rules.selecteddeparts }]"></wd-picker>
				</wd-cell-group>
				<view class="footer p5">
					<wd-button type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
					<wd-button type="info" size="large" @click="handleCancel" block>取消</wd-button>
				</view>
			</view>
		</wd-form>
		<!-- 碳商信息认证 -->
		<wd-form v-else style="z-index: 999;" custom-class="pt3" ref="form" :model="model">
			<view class="change-info-box">
				<wd-cell-group border>
					<wd-input required label="碳商标识：" prop="carbonSign" clearable label-width="150px"
						v-model="model.carbonSign" placeholder="请输入碳商标识" :rules="[{ validator: rules.carbonSign }]">
					</wd-input>
					<wd-input required label="公司统一信用代码：" prop="creditCode" clearable label-width="150px"
						v-model="model.creditCode" placeholder="请输入公司统一信用代码" :rules="[{ validator: rules.creditCode }]">
					</wd-input>
					<wd-picker @confirm="provincelistHandleConfirm" :columns="provincelistColumns" required label="省份："
						prop="province" clearable label-width="150px" v-model="model.province" placeholder="请输入省份"
						:rules="[{ validator: rules.province }]">
					</wd-picker>
					<wd-picker @confirm="cityHandleConfirm" :columns="cityColumns" required label="城市：" prop="city"
						clearable label-width="150px" v-model="model.city" placeholder="请输入城市"
						:rules="[{ validator: rules.city }]">
					</wd-picker>
					<wd-picker @confirm="countyHandleConfirm" :columns="countyColumns" required label="地区："
						prop="district" clearable label-width="150px" v-model="model.district" placeholder="请输入地区"
						:rules="[{ validator: rules.district }]">
					</wd-picker>
					<wd-textarea :rules="[{ validator: rules.address }]" placeholder="..." prop="address" required
						label="详细地址：" clearable v-model="model.address" auto-height />
				</wd-cell-group>
				<view class="footer p5">
					<wd-button type="primary" size="large" @click="handleSubmit" block>确认</wd-button>
					<wd-button type="info" size="large" @click="handleCancel" block>取消</wd-button>
				</view>
			</view>
		</wd-form>
	</PageLayout>
</template>

<script lang="ts" setup>
	import { ref, reactive, nextTick, onMounted } from 'vue'
	import { http } from '@/utils/http'
	import { useToast, useMessage, useNotify, dayjs } from 'wot-design-uni'
	import { useRouter } from '@/plugin/uni-mini-router'
	import { useUserStore } from '@/store/user'
	import { getFileAccessHttpUrl } from '@/common/uitls'
	import { onShow } from '@dcloudio/uni-app'

	defineOptions({
		name: 'chatList',
		options: {
			styleIsolation: 'shared',
		},
	})
	const toast = useToast()
	const router = useRouter()
	const userStore = useUserStore()
	const model = ref({
		carbonSign: '', // 碳商标识
		creditCode: '', // 统一信用代码
		province: '', // 省份
		city: '', // 城市
		district: '', // 地区
		address: "", // 详细地址
	})
	const copyModel = ref({})
	const userModel = reactive({
		userName: '', // 用户名
		selecteddeparts: '' // 所属公司
	})
	const showPasswordFlag = ref(true)
	const pageTitle = ref('')
	const userForm = ref(null)
	const columns = ref([])
	const applyUrl = ref('')
	const carbonUpdate = ref(false)
	const addressAreaListUrl = reactive({
		"provincelist": '/region/region/provincelist',
		"city": '/region/region/citylist',
		"county": '/region/region/countylist',
	})
	const provincelistColumns = ref([])
	const provincelistList = ref([])
	const cityColumns = ref([])
	const cityList = ref([])
	const countyColumns = ref([])
	const countyList = ref([])

	const rules = {
		carbonSign: (value) => {
			if (value?.trim()?.length) {
				return true
			} else {
				toast.warning('请输入碳商标识')
				return false
			}
		},
		creditCode: (value) => {
			if (value?.trim()?.length) {
				if (!/^[0-9A-HJ-NPQRTUWXY]{18}$/.test(value)) {
					toast.warning('统一信用代码格式不正确')
					return false;
				}
				return true
			} else {
				toast.warning('请输入公司统一信用代码')
				return false
			}
		},
		province: (value) => {
			if (value?.trim()?.length) {
				return true
			} else {
				toast.warning('请输入省份')
				return false
			}
		},
		city: (value) => {
			if (value?.trim()?.length) {
				return true
			} else {
				toast.warning('请输入城市')
				return false
			}
		},
		district: (value) => {
			if (value?.trim()?.length) {
				return true
			} else {
				toast.warning('请输入地区')
				return false
			}
		},
		address: (value) => {
			if (value?.trim()?.length) {
				return true
			} else {
				toast.warning('请输入详细地址')
				return false
			}
		},
		userName: (value) => {
			if (value?.trim()?.length) {
				return true
			} else {
				toast.warning('请输入用户名称')
				return false
			}
		},
		selecteddeparts: (value) => {
			if (value?.trim()?.length) {
				return true
			} else {
				toast.warning('请选择所属公司')
				return false
			}
		}
	}
	const form = ref()

	function showPassword(e) {
		console.log(e, "点击小眼睛");
	}

	function handleSubmit() {
		form.value
			.validate()
			.then(({ valid, errors }) => {
				if (valid) {
					// return
					uni.showModal({
						content: carbonUpdate.value ? "确认提交资料吗？" : "确认修改信息吗？",
						confirmText: "确认",
						confirmColor: "#2fd4ae",
						success(res) {
							if (res.confirm) {
								submitChangeAuth()
							}
						}
					})
				}
			})
			.catch((error) => {
				console.log(error, 'error')
			})
	}

	const submitChangeAuth = async () => {
		let data
		uni.showLoading()
		if (userStore.userInfo.isUser == '1') {
			data = {
				...userModel,
				id: userStore.userInfo.userid,
				// carbonName: columns.value.find(item => item.value == userModel.selecteddeparts).label
			}
		} else {
			data = {
				...model.value,
				accountId: userStore.userInfo.userid,
				carbonName: userStore.userInfo.username
			}
		}
		// return
		try {
			let res : any = null
			if (userStore.userInfo.isUser == '1') {
				res = await http.put(applyUrl.value, data)
			} else {
				res = carbonUpdate.value ? await http.put(applyUrl.value, data) : await http.post(applyUrl.value, data)
			}
			console.log(res, '999999999999999999');
			if (res.code != 200) {
				uni.hideLoading()
				toast.warning(res.message)
				return
			}
			uni.hideLoading()
			toast.success('操作成功~')
			setTimeout(() => {
				router.replaceAll({ name: 'people' })
			}, 1000)
		} catch (err) {
			uni.hideLoading()
			toast.error(err.message)
		}
	}

	function handleCancel() {
		let canNavBack = getCurrentPages()
		if (canNavBack && canNavBack.length > 1) {
			uni.navigateBack()
		} else {
			history.back();
		}
	}

	// 公司信息获取
	const getCompanyDate = () => {
		// /zbCarbonMerchant/zbCarbonMerchant/list
		http.get('/sys/sysDepart/getDepart').then((res : any) => {
			if (res.success && res.result.length > 0) {
				let areas = res.result.map(info => ({
					label: info.departName,
					value: info.id
				}));
				columns.value = areas
			}
			console.log("carbon---------------------------->", columns.value, res);
		})

	}

	// 碳商信息初始化
	const isCarbonBuiess = async () => {
		uni.showLoading({
			title: "加载中"
		})
		try {
			await getProvincelistList()
			const res : any = await http.get("/zbCarbonMerchant/zbCarbonMerchant/list", { accountId: userStore.userInfo.userid })
			const buiess = res.result.records
			if (buiess.length) {
				model.value = buiess[0]
				copyModel.value = buiess[0]
				await getCityList(provincelistList.value.find(item => item.name == model.value.province).id)
				await getCountyList(cityList.value.find(item => item.name == model.value.city).id)
				carbonUpdate.value = true
				applyUrl.value = "/zbCarbonMerchant/zbCarbonMerchant/edit"
				uni.hideLoading()
			} else {
				carbonUpdate.value = false
				applyUrl.value = "/zbCarbonMerchant/zbCarbonMerchant/add"
				uni.hideLoading()
			}
		} catch (error) {
			uni.hideLoading()
			toast.warning(error.message)
		}
	}

	// 用户信息认证接口初始化
	const isUserBuiess = async () => {
		uni.showLoading({
			title: "加载中"
		})
		try {
			getCompanyDate()
			applyUrl.value = "/sys/user/AppEdit"
			const res : any = await http.get("/sys/api/getDepartIdsByUserId", { userId: userStore.userInfo.userid })
			console.log("res------------user------------->", res);
			res.length && (userModel.selecteddeparts = res[0])
			uni.hideLoading()
			// const buiess = res.result.records
			// if (buiess.length) {
			// 	userModel.selecteddeparts = buiess[0].selecteddeparts
			// 	uni.hideLoading()
			// } else {
			// 	applyUrl.value = "/zbUserCarbon/zbUserCarbon/edit"
			// 	applyUrl.value = "/zbUserCarbon/zbUserCarbon/add"
			// 	applyUrl.value = "/sys/user/AppEdit"
			// /zbUserCarbon/zbUserCarbon/list
			// }
		} catch (error) {
			uni.hideLoading()
			toast.warning(error.message)
		}
	}

	// 省
	const getProvincelistList = async () => {
		try {
			const res : any = await http.get(addressAreaListUrl.provincelist)
			console.log("area------------>", res);
			provincelistList.value = res.result
			provincelistColumns.value = provincelistList.value.map(item => {
				return {
					label: item.name,
					value: item.name
				}
			})
		} catch (error) { }
	}
	// 市
	const getCityList = async (id) => {
		try {
			const res : any = await http.get(addressAreaListUrl.city, { parentId: id })
			console.log("area------------>", res);
			cityList.value = res.result
			cityColumns.value = cityList.value.map(item => {
				return {
					label: item.name,
					value: item.name
				}
			})
		} catch (error) { }
	}
	// 区
	const getCountyList = async (id) => {
		try {
			const res : any = await http.get(addressAreaListUrl.county, { parentId: id })
			console.log("area------------>", res);
			countyList.value = res.result
			countyColumns.value = countyList.value.map(item => {
				return {
					label: item.name,
					value: item.name
				}
			})
		} catch (error) { }
	}

	function provincelistHandleConfirm({ value }) {
		console.log(value)
		const id = provincelistList.value.find(item => item.name == value).id
		model.value.city = ""
		model.value.district = ""
		getCityList(id)
	}

	function cityHandleConfirm({ value }) {
		console.log(value)
		const id = cityList.value.find(item => item.name == value).id
		model.value.district = ""
		getCountyList(id)
	}

	function countyHandleConfirm({ value }) {
		console.log(value)
	}

	onShow(() => {
		pageTitle.value = userStore.userInfo.isUser == '1' ? '用户信息认证' : '碳商信息认证'
		userForm.value = userStore.userInfo.isUser == '1' ? true : false
		userModel.userName = userStore.userInfo.username
		userStore.userInfo.isUser == '1' ? isUserBuiess() : isCarbonBuiess()
		console.log(userStore.userInfo, 'userInfo--------------');
	})
</script>

<style lang="scss" scoped>
	.change-password-container {
		width: 100%;
		height: 100%;
		box-sizing: border-box;
		padding: 10px;
		background-color: #FFF;
		display: flex;
		flex-direction: column;
		gap: 10px;

		display: flex;
	}

	.footer {
		display: flex;
		flex-direction: column;
		gap: 20upx;
	}

	.change-info-box {
		box-sizing: border-box;
		background-color: #FFF;
		padding: 26upx;
		height: 100%;
	}



	:deep(.wd-cell-group) {
		box-sizing: border-box;
		border: 4upx solid #eff2f1;
		border-radius: 20upx;
		--wot-input-color: var(--color-grey);
		--wot-cell-value-color: var(--color-grey);
		background-color: transparent !important;
		--wot-cell-title-color: var(--UI-FG-0);

		.wd-input__label {
			--wot-cell-title-color: var(--UI-FG-0);
		}

		.wd-cell__left {
			color: var(--UI-FG-0);
		}

		.wd-select-picker__cell {
			--wot-cell-wrapper-padding: 14px;
		}

		.wd-select-picker {
			// margin: 15px 0;
		}

		.wd-cell-group__body {
			background-color: transparent;
		}
	}

	:deep(.wd-cell) {
		.wd-cell__wrapper {
			align-items: center;
		}

		.wd-cell__left {
			display: flex;
			align-items: center;
			width: 70px;
			flex: none;
		}

		.wd-cell__value {
			text-align: left;
		}
	}

	:deep(.pt3) {
		padding-top: 0;
		height: 100%;
	}

	:deep(.p5) {
		padding: 0;
		padding-top: 26upx;
	}
</style>